package com.ruoyi.security.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.security.domain.AfElevator;
import com.ruoyi.security.domain.AfElevatorHistory;
import com.ruoyi.security.domain.ElevatorResult1;
import com.ruoyi.security.elevator.util.ElevatorInterfaceUtil;
import com.ruoyi.security.service.IAfElevatorHistoryService;
import com.ruoyi.security.service.IAfElevatorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 电梯运行历史Controller
 *
 * @author cjie
 * @date 2022-07-27
 */
@Api(tags = " 电梯运行历史")
@RestController
@RequestMapping("/afElevatorHistory")
public class AfElevatorHistoryController extends BaseController {
    @Autowired
    private IAfElevatorHistoryService afElevatorHistoryService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IAfElevatorService afElevatorService;

    /**
     * 查询电梯运行历史列表
     */
    @ApiOperation(value="查询电梯运行历史列表", notes="查询电梯运行历史列表")
    @PreAuthorize(hasPermi = "security:afElevatorHistory:list")
    @GetMapping("/list")
    public TableDataInfo list(AfElevatorHistory afElevatorHistory) {
        startPage();
        List<AfElevatorHistory> list = afElevatorHistoryService.selectAfElevatorHistoryList(afElevatorHistory);
        return getDataTable(list);
    }

    /**
     * 导出电梯运行历史列表
     */
    @ApiOperation(value="导出电梯运行历史列表", notes="导出电梯运行历史列表")
    @PreAuthorize(hasPermi = "security:afElevatorHistory:export")
    @Log(title = "电梯运行历史", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AfElevatorHistory afElevatorHistory) throws IOException {
        List<AfElevatorHistory> list = afElevatorHistoryService.selectAfElevatorHistoryList(afElevatorHistory);
        ExcelUtil<AfElevatorHistory> util = new ExcelUtil<AfElevatorHistory>(AfElevatorHistory.class);
        util.exportExcel(response, list, "电梯运行历史数据");
    }
    /**
     * 获取电梯运行历史详细信息
     */
    @ApiOperation(value="获取电梯运行历史详细信息", notes="获取电梯运行历史详细信息")
    @PreAuthorize(hasPermi = "security:afElevatorHistory:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(afElevatorHistoryService.selectAfElevatorHistoryById(id));
    }

    /**
     * 新增电梯运行历史
     */
    @ApiOperation(value="新增电梯运行历史", notes="新增电梯运行历史")
    @PreAuthorize(hasPermi = "security:afElevatorHistory:add")
    @Log(title = "电梯运行历史", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AfElevatorHistory afElevatorHistory) {
        return toAjax(afElevatorHistoryService.insertAfElevatorHistory(afElevatorHistory));
    }

    /**
     * 修改电梯运行历史
     */
    @ApiOperation(value="修改电梯运行历史", notes="修改电梯运行历史")
    @PreAuthorize(hasPermi = "security:afElevatorHistory:edit")
    @Log(title = "电梯运行历史", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AfElevatorHistory afElevatorHistory) {
        return toAjax(afElevatorHistoryService.updateAfElevatorHistory(afElevatorHistory));
    }

    /**
     * 删除电梯运行历史
     */
    @ApiOperation(value="删除电梯运行历史", notes="删除电梯运行历史")
    @ApiImplicitParam(name = "ids", value = "电梯运行历史ID数组", required = true,paramType = "path", allowMultiple=true, dataType = "String")
    @PreAuthorize(hasPermi = "security:afElevatorHistory:remove")
    @Log(title = "电梯运行历史", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(afElevatorHistoryService.deleteAfElevatorHistoryByIds(ids));
    }

    /**
     * 同步电梯运行历史
     */
    @ApiOperation(value="同步电梯运行历史", notes="同步电梯运行历史")
    @GetMapping("/syncInfo")
    public R syncInfo(String queryDate) {
        String token = redisService.getCacheObject("elevator_token");
        if (StringUtils.isBlank(token)){
            return R.fail("梯联网token为空");
        }

        //查询电梯列表 factoryNO数组;
        AfElevator afElevator = new AfElevator();
        afElevator.setElevStatus("1");
        List<AfElevator> afElevatorList = afElevatorService.selectAfElevatorList(afElevator);
        List<String> test = new ArrayList<>(afElevatorList.size());
        for(AfElevator afElevator1:afElevatorList){
            // factoryNo
            test.add(afElevator1.getFactoryNo());
        }
        ElevatorResult1<AfElevatorHistory> result = ElevatorInterfaceUtil.getHistoryRunningDataList(test.toArray(new String[test.size()]), queryDate,token,null);
         if ("0".equals(result.getErrorCode())){
                List<AfElevatorHistory> list = result.getData();
                if(StringUtils.isBlank(queryDate)){
                    //实时数据处理
                    list.stream().forEach(o ->{
                        //afElevatorMaintenanceService.insertAfElevatorMaintenance(o);
                        afElevatorList.stream().forEach(afElevator2->{
                            if(afElevator2.getFactoryNo().equals(o.getFactoryNO())){
                                o.setRunCount(o.getRunCount()-afElevator2.getRunCount());
                                o.setRunTime(o.getRunTime()-afElevator2.getRunTime());
                                // 查询，不存在 插入，存在更新
                                List<AfElevatorHistory> list1 = afElevatorHistoryService.selectAfElevatorHistoryList(o);
                                if(list1 == null || list1.size()==0){
                                    afElevatorHistoryService.insertAfElevatorHistory(o);
                                }else {
                                    o.setId(list1.get(0).getId());
                                    afElevatorHistoryService.updateAfElevatorHistory(o);
                                }

                            }
                        });

                    });
                }else{
                    //历史数据处理，更新电梯列表
                    list.forEach(o->{
                        afElevatorList.stream().forEach(afElevator2->{
                            if(afElevator2.getFactoryNo().equals(o.getFactoryNO())){
                                afElevator2.setRunCount(o.getRunCount());
                                afElevator2.setRunTime(o.getRunTime());
                                afElevatorService.updateAfElevator(afElevator2);
                            }
                        });

                    });
                }

          return R.ok();

         }else {
                logger.error("error ==>" + result.getErrorMsg());
                return R.fail(result.getErrorMsg());
         }

    }

}
